// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})


const db = cloud.database();
const _ = db.command;
// 云函数入口函数
exports.main = async (event, context) => {
  /**
   * 获取当前增在播放的音乐和未播放音乐
   */
  let playmusic = await db.collection('MUSIC_LOG').where({
    playstatus:_.eq(1).or(_.eq(0))
  }).limit(10).orderBy('date','asc').orderBy('playstatus','desc').get();
  console.log(playmusic.data)
  if(playmusic.data.length == 0) {
    //随机选取一个音乐播放
    
    return;
  }
  else{
    let onplaymusic = playmusic.data[0]
    if(onplaymusic.playlength > onplaymusic.length){
      //将该歌曲状态修改为已播放
      console.log(onplaymusic.name+'播放完了')
      db.collection('MUSIC_LOG').doc(onplaymusic._id).update({
        data:{
          playstatus:2
        }
      })
      //寻找下一首歌曲 配置为可播
      let musiclist = playmusic.data
      var index = 0;
      if(musiclist.length == 0) return
      for(var i=1;i<musiclist.length;i++){
        if(musiclist[i].playstatus == 0){
          index = i
          break
        }
      }
      if(index == 0) return
      let selmusic = musiclist[index]
      console.log(selmusic.name+'被设置为正在播放歌曲')
      db.collection('MUSIC_LOG').doc(selmusic._id).update({
        data:{
          playstatus:1
        }
      })
    }else{
      //还有播放完成 数值上增加 10S
      console.log(onplaymusic.name+'已经播放了'+onplaymusic.playlength+'s')
      db.collection('MUSIC_LOG').doc(onplaymusic._id).update({
        data:{
          playlength:_.inc(10),
          playstatus:1
        }
      })
    }
  }
}